﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Consul;
using LoginService.Models;
using Microsoft.AspNetCore.Mvc;

namespace LoginService.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        [HttpPost(nameof(RequestToken))]
        public async Task<ActionResult> RequestToken(LoginRequest loginRequest)
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict["client_id"] = "HYD-PC-101";
            dict["client_secret"] = "HYD-PC-101:123654";
            dict["grant_type"] = "password";

            dict["username"] = loginRequest.UserName;
            dict["password"] = loginRequest.Password;

            Console.WriteLine($"用户名：{loginRequest.UserName}，密码:{loginRequest.Password}");

            //由登录服务器向IdentityServer发请求获取Token

            #region ===1===

            //using (HttpClient http = new HttpClient())
            //{
            //    using (var formUrlEncodedContent = new FormUrlEncodedContent(dict))
            //    {
            //        var msg = await http.PostAsync("http://127.0.0.1:30221/connect/token", formUrlEncodedContent);

            //        string result = await msg.Content.ReadAsStringAsync();

            //        return Content(result, "application/json");
            //    }
            //}
            #endregion

            #region ===2===

            using (var consulClient = new ConsulClient(x =>
            {
                x.Address = new Uri("http://127.0.0.1:8500");
            }))
            {
                var consulServices = consulClient.Agent.Services().Result.Response;

                var identityServer4V2Services = consulServices.Values.Where(x => x.Service.Equals("IdentityServer4V2Service", StringComparison.OrdinalIgnoreCase));


                var randomIdentityServer4V2ServiceIndex = DateTime.Now.Second % identityServer4V2Services.Count();

                var randomIdentityServer4V2Service = identityServer4V2Services.ElementAt(randomIdentityServer4V2ServiceIndex);

                Console.WriteLine(
                    $"Index:{randomIdentityServer4V2ServiceIndex}," +
                    $"ID:{randomIdentityServer4V2Service.ID}," +
                    $"Service:{randomIdentityServer4V2Service.Service}," +
                    $"Address:{randomIdentityServer4V2Service.Address}," +
                    $"Port:{randomIdentityServer4V2Service.Port}"
                    );

                using (var httpClient = new HttpClient())
                {
                    using (var formUrlEncodedContent = new FormUrlEncodedContent(dict))
                    {
                        var msg = await httpClient.PostAsync(
                            $"http://{randomIdentityServer4V2Service.Address}:{randomIdentityServer4V2Service.Port}/connect/token",
                            formUrlEncodedContent
                            );

                        string result = await msg.Content.ReadAsStringAsync();

                        return Content(result, "application/json");
                    }
                }
            }

            #endregion

            #region ===3===

            //using (var httpClient = new HttpClient())
            //{
            //    using (FormUrlEncodedContent formUrlEncodedContent = new FormUrlEncodedContent(dict))
            //    {
            //        var restTemplateClient = new RestTemplate(httpClient)
            //        {
            //            ConsulServerUrl = "http://127.0.0.1:8500"
            //        };

            //        HttpRequestMessage httpRequestMessage = new HttpRequestMessage();
            //        httpRequestMessage.RequestUri = new Uri($"http://IdentityServer4V2Service/Connect/Token");
            //        httpRequestMessage.Method = HttpMethod.Post;
            //        httpRequestMessage.Content = formUrlEncodedContent;

            //        httpRequestMessage.Headers.Add("Content-Type", "form-data");

            //        var response = restTemplateClient.SendAsync(httpRequestMessage).Result;

            //        Console.WriteLine(response.StatusCode);

            //        return Content(response.StatusCode.ToString(), "application/json");
            //    }
            //} 
            #endregion
        }
    }
}